<?php

namespace app\service;

use app\ErrorCode;
use app\exception\ApiException;
use app\model\Department;
use app\traits\Singleton;

class DepartmentService
{
    use Singleton;

    public function getDepartmentList($name, $code, $page, $pageSize)
    {
        $model = Department::with(["allChildren"])
            ->where("pid", "=", 0)
            ->where('is_delete', "=", 0)
            ->order('sort', 'desc');

        if ($name) {
            $model->where('name', 'like', "%{$name}%");
        }

        if ($code) {
            $model->where('code', 'like', "%{$code}%");
        }

        $paginator = $model->page($page)
            ->paginate($pageSize);

        $data = array_map(function ($item) {
            return $item;
        }, $paginator->getCollection()->toArray());

        return [
            'list' => $data,
            'total' => $paginator->total(),
        ];
    }

    public function getDepartmentInfo($departmentId)
    {
        return Department::where('id', $departmentId)
            ->where('is_delete', "=", 0)
            ->find();
    }

    public function getDropdownDepartmentList()
    {
        return Department::with(["allChildren"])
            ->where("pid", "=", 0)
            ->where('is_delete', "=", 0)
            ->field(["id", "name"])
            ->select()
            ->toArray();
    }

    public function createDepartment($name, $code, $pId)
    {
        return Department::create([
            'name' => $name,
            'code' => $code,
            'pid' => $pId,
        ]);
    }

    public function updateDepartment($id, $name, $code, $pId)
    {
        return Department::update([
            'name' => $name,
            'code' => $code,
            'pid' => $pId,
        ], [
            'id' => $id,
        ]);
    }

    public function deleteDepartment($id)
    {
        $children = Department::where('pid', '=', $id)->find();
        if ($children) {
            throw new ApiException('请先删除子部门', ErrorCode::BUSINESS);
        }
        return Department::update([
            'is_delete' => 1,
            'delete_time' => time(),
        ], [
            'id' => $id,
        ]);
    }

    public function getDepartmentData($name, $code)
    {
        $model = Department::with(["allChildren"])
            ->where("pid", "=", 0)
            ->where('is_delete', "=", 0)
            ->field(["id", "name", "code"])
            ->order('sort', 'desc');
        if ($name) {
            $model->where('name', 'like', "%{$name}%");
        }

        if ($code) {
            $model->where('code', 'like', "%{$code}%");
        }

        return $model->select()->toArray();
    }
}